package net.heimeng.bphelper;

import static dev.langchain4j.data.message.UserMessage.userMessage;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.zhipu.ZhipuAiChatModel;
import dev.langchain4j.service.SystemMessage;

@SystemMessage("现在你是一个具有10年经验的王者荣耀bp冠军教练，现在我需要你的帮助。")
public class BPService {
    private final ChatLanguageModel model = ZhipuAiChatModel.builder()
            .apiKey("ad041e17201c72c3f700d08bdf1ad6cd.w8aC802PjqYApXdz")
            .model("GLM-4-0520")
            .build();
    private final ChatMemory chatMemory = MessageWindowChatMemory.withMaxMessages(100);
    private boolean isBlue;
    public BPInfo redTeam = new BPInfo();
    public BPInfo blueTeam = new BPInfo();
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * 与 AI 聊天
     *
     * @param message 用户发送的消息
     * @return AI 返回的消息
     */
    public String chat(String message) {
        Future<String> future = executorService.submit(() -> {
            synchronized (chatMemory) {
                chatMemory.add(userMessage(message));
            }
            try {
                AiMessage answer = model.generate(chatMemory.messages()).content();
                synchronized (chatMemory) {
                    chatMemory.add(answer);
                }
                return answer.text();
            } catch (Exception e) {
                e.printStackTrace();
                return "An error occurred while processing your message.";
            }
        });
        try {
            return future.get();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将目前的 BP 情况发送给 AI
     *
     * @return AI 返回的消息
     */
    public String submit() {
        String prompts = isBlue ? "我" : "对" + "方是蓝色方，后手禁用英雄，先手选择英雄。" +
                "下面我将告诉你目前红蓝双方的BP情况，请帮助我进行BP。\n";
        prompts += "红色方：" + redTeam.toString() + "\n";
        prompts += "蓝色方：" + blueTeam.toString() + "\n";
        prompts += "字数要求：请用词简练，必须控制在80字以内。";
        return chat(prompts);
    }

    public BPService(boolean isBlue) {
        this.isBlue = isBlue;
    }

    public boolean isBlue() {
        return isBlue;
    }

    public void setBlue(boolean flag) {
        isBlue = flag;
    }
}
